<template>
  <div>
    <main-content :title="`${Route.query.id ? '编辑' : '添加'}智能客群`" back>
      <el-form
        v-loading="loading"
        style="width: 500px"
        ref="formDataRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="所属机构" prop="insId">
          <el-select
            v-model="formData.insId"
            placeholder="请选择所属机构"
            clearable
            style="width: 100%"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              :key="item.id"
              v-for="item in orgList"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客群名称" prop="name">
          <el-input
            type="text"
            placeholder="请输入客群名称"
            v-model.trim="formData.name"
            maxlength="20"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="设为动态客群" prop="type">
          <el-switch
            v-model="formData.type"
            :disabled="formData.id"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item> -->
        <el-form-item label="选择分组" prop="categoryId">
          <TreeSelect
            class="_tree_select"
            v-model="formData.categoryId"
            :treeSelectData="treeSelectData"
            :treeProps="{
              label: 'name',
              disabled: (data: any) => {
                return Boolean(data.nodeType && !data.children);
              },
            }"
            placeholder="请选择分组"
          ></TreeSelect>
        </el-form-item>
        <el-form-item label="客群标识" prop="symbol" v-if="formData.id">
          <el-input
            type="text"
            placeholder="请输入客群标识"
            v-model="formData.symbol"
            maxlength="50"
            :show-word-limit="true"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="客群用途" prop="remark">
          <el-input
            type="textarea"
            placeholder="请输入客群用途"
            v-model="formData.remark"
            maxlength="50"
            show-word-limit
          >
          </el-input>
        </el-form-item>
      </el-form>

      <div class="m-l">
        <Limits v-model="limitsList" :disabled="Route.query.id ? true : false" :options="['tagLimit']"></Limits>
      </div>
      <div class="m-l">
        <el-button type="primary" @click="formValidate">确定</el-button>
        <el-button @click="goBack">取消</el-button>
      </div>
    </main-content>
  </div>
</template>
<script lang="ts" setup>
import Limits from "@/components/limits/Index.vue";
import TreeSelect from "@/components/TreeSelect/TreeSelect.vue";
import CustomerApi from "@/api/customerApi";
import { allOrg } from "@/api/orgManage";
const Router = useRouter(),
  Route = useRoute();
const formData = ref({
  id: "",
  insName: "",
  type: 1,
  syncStatus: 0,
  insId: "",
  name: "",
  symbol: "",
  remark: "",
  conditionalOriginal: "",
  categoryId: "",
});
const rules = {
  insId: [{ required: true, message: "请输入所属机构", trigger: "blur" }],
  name: [{ required: true, message: "请输入客群名称", trigger: "blur" }],
  symbol: [{ required: true, message: "请输入客群标识", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择分组", trigger: "blur" }],
};
const loading = ref(false)
const formDataRef = ref();
const limitsList = ref({});
const treeSelectData = ref([] as any);
const orgList = ref([] as any);

// 获取机构
const getOrgList = async () => {
  const rs = await allOrg();
  if (rs.code == 200) {
    orgList.value = rs.payload;
  }
};
// 获取客群分组
const getCustomersGroupTree = async () => {
  let rs = await CustomerApi.getCustomersGroupTree({});
  if (rs.code === 200) {
    treeSelectData.value = rs.payload;
  }
};
// 获取客群信息
const getInfoGroup = async () => {
  let rs = await CustomerApi.getInfoGroup({ id: Route.query.id });
  if (rs.code === 200) {
    
    formData.value.id = rs.payload.id;
    formData.value.syncStatus = rs.payload.syncStatus
    formData.value.insName = rs.payload.insName;
    formData.value.insId = rs.payload.insId;
    formData.value.name = rs.payload.name;
    formData.value.symbol = rs.payload.symbol;
    formData.value.conditionalOriginal = rs.payload.conditionalOriginal;
    formData.value.categoryId = rs.payload.categoryId;
    formData.value.remark = rs.payload.remark;
    limitsList.value = rs.payload.conditionalOriginal
      ? JSON.parse(rs.payload.conditionalOriginal)
      : {};
  }
};
const goBack = () => {
  Router.go(-1);
};
const formValidate = () => {
  formDataRef.value.validate((valid: any) => {
    if (valid) {
      submit();
    } else {
      return false;
    }
  });
};
const submit = async () => {
  if (!limitsList.value || JSON.stringify(limitsList.value) == "{}") {
    ElMessage.warning("请创建智能客群的规则");
    return;
  }

  let params = JSON.parse(JSON.stringify(formData.value));
  params.conditionalOriginal = JSON.stringify(limitsList.value);
  let rs = await CustomerApi.addUserGroup(params);
  if (rs.code == 200) {
    ElMessage.success(formData.value.id ? "编辑智能客群成功" : "添加智能客群成功");
    goBack();
  }
};

onBeforeMount( async() => {
  loading.value = true
  await getOrgList(); // 获取机构
  await getCustomersGroupTree(); // 获取客群分组
  if (Route.query.id) {
    await getInfoGroup(); // 获取客群信息
  }
  loading.value = false
});
</script>

<style lang="scss" scoped>
._tree_select {
  width: 100%;
}
.m-l {
  margin-left: 100px;
  margin-bottom: 20px;
}
</style>
